/*
    Geocache: some utilities for managing and visualizing geocache information
    Copyright (C) 2008  Gary Jackson

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*
 * ZipStreamToFiles.java
 */

package com.thegbomb.geocache;

import com.thegbomb.common.*;
import com.thegbomb.common.Mapper;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.log4j.Logger;

/**
 *
 * @author Gary Jackson
 */
public class ZipStreamToFiles implements Mapper<ZipInputStream, File> {
    private static final Logger logger = Logger.getLogger(ZipStreamToFiles.class);
    private static final Pattern ANY = Pattern.compile("");
    private Pattern pattern;
    private File base;
    
    public ZipStreamToFiles(Pattern pattern, File base) {
        this.base = base;
        this.pattern = pattern;
    }
    
    /**
     * Creates a new instance of ZipStreamToFiles that will return parts where the
     * MIME-type matches the given pattern.
     */
    public ZipStreamToFiles(Pattern pattern) {
        this(pattern, new File("."));
    }
    
    /**
     * Convenience constructor identical to:
     * new ZipStreamToFiles(Pattern.compile(regex))
     */
    public ZipStreamToFiles(String regex) {
        this(Pattern.compile(regex));
    }
    
    /**
     * Creates a new instance of ZipStreamToFiles that will return all leaf parts.
     */
    public ZipStreamToFiles() {
        this(ANY);
    }
    
    public Iterator<File> map(ZipInputStream input) {
        ZipEntry ze;
        Collection<File> output = new LinkedList<File>();
        
        try {
            while ((ze = input.getNextEntry()) != null) {
                String name = ze.getName();
                if (pattern.matcher(name).matches()) {
                    File f = new File(base, name);
                    writeOut(f, input);
                    output.add(f);
                }
            }
            
            input.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        
        return output.iterator();
    }
    
    private void writeOut(File output, InputStream inputStream) throws IOException {
        InputStream is;
        OutputStream os = new BufferedOutputStream(new FileOutputStream(output));
        
        if (inputStream instanceof BufferedInputStream)
            is = inputStream;
        else
            is = new BufferedInputStream(inputStream);
        
        byte[] buf = new byte[4096];
        
        int len = 0;
        while ((len = is.read(buf)) > -1) {
            os.write(buf, 0, len);
        }
        os.flush();
        os.close();
    }
}
